import type { MaybeRefOrGetter } from 'vue'
import { cloneDeep } from 'lodash-es'
import { screenAllYear } from '@/api/screen'

export default function useAnnualConsumptionChart(n: MaybeRefOrGetter<number> = 300) {
  const title = ref('')
  const data = shallowRef<{ name: string, value: [string, number] }[]>([])
  const sliceData = computed(() => {
    return unref(data).slice(0, toValue(n))
  })
  const unit = ref('')
  const copy = shallowRef<{ name: string, value: [string, number] }[]>([])
  const total = ref(0)

  const getAnnualConsumptionChartData = async () => {
    try {
      const res = await screenAllYear()
      const results: { name: string, value: [string, number] }[] = []
      const serie = res.data.series[0]
      const x = res.data.xaxis.data || []
      for (let i = 0; i < x.length; i++) {
        results.push({
          name: x[i],
          value: [x[i], serie.data[i]],
        })
      }

      total.value = x.length
      unit.value = serie.unit
      title.value = res.data.name
      data.value = results
      copy.value = cloneDeep(results)
    }
    catch (e) {
      console.warn(e)
    }
  }

  let timer: ReturnType<typeof setInterval>
  const start = async (cb?: () => void) => {
    await getAnnualConsumptionChartData()
    cb?.()
    let count = 0
    timer = setInterval(() => {
      if (count >= unref(total) - toValue(n)) {
        count = 0
        data.value = cloneDeep(copy.value)
        return
      }
      count++
      const d = unref(data)
      const r = [...d.slice(1), d[0]]
      data.value = r
    }, 1e3)
  }

  onBeforeUnmount(() => {
    timer && clearInterval(timer)
  })

  return {
    data,
    sliceData,
    title,
    unit,
    getAnnualConsumptionChartData,
    start,
  }
}
